﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ERPStudio;
using System.Data.SqlClient;

namespace ExBug
{
    public partial class PACFrm : FrmWorkspace
    {
        private PACRezFrm _frmNCR = null;
        private Int16 AnulCurent = 0;
        private Int16 LunaCurenta = 0;
        private String SerieNumerica = String.Empty;
        private String SerieNumericaCFP = String.Empty;
        private int NoRecAdd = 0;
        private List<BindingSource> listBS = new List<BindingSource>();
        private List<SqlDataAdapter> listTA = new List<SqlDataAdapter>();

        public PACFrm(ModuleClass mInfo)
            : base(mInfo)
        {
            InitializeComponent();
            this.HandleAfterAdd += new AfterAddHandler(PACFrm_HandleAfterAdd);
            this.HandleTiparire += new EventHandler(PACFrm_HandleTiparire);
            this.HandleRezumat += PAC_HandleRezumat;
            eSRPDataSet.PropunereAngajareCheltuiala.DataColumn.DefaultValue = DateTime.Now;
            eSRPDataSet.PropunereAngajareCheltuiala.CodUnitateColumn.DefaultValue = ModuleInfo.CodUnitate;
            eSRPDataSet.PropunereAngajareCheltuiala.DataVizaCFPColumn.DefaultValue = DateTime.Now;
            eSRPDataSet.PropunereAngajareCheltuiala.VizatCFPColumn.DefaultValue = true;
            eSRPDataSet.PropunereAngajareCheltuiala.MotivRefuzColumn.DefaultValue = String.Empty;
            eSRPDataSet.PropunereAngajareCheltuiala.SumaTotalaColumn.DefaultValue = 0;
            PACDetaliuDGV.m_AutoCompletionColumns.Add(artAlColumn);
            PACDetaliuDGV.m_AutoCompletionColumns.Add(capitolColumn);
            propunereAngajareCheltuialaTableAdapter.Adapter.RowUpdated += new SqlRowUpdatedEventHandler(Adapter_RowUpdated);
            lstPK.Add(numarTB);
            dataDTP.Format = DateTimePickerFormat.Custom;
            dataDTP.CustomFormat = "dd.MM.yyyy";
            dataVizaCFPDTP.Format = DateTimePickerFormat.Custom;
            dataVizaCFPDTP.CustomFormat = "dd.MM.yyyy";
        }

        void PAC_HandleRezumat(object sender, EventArgs e)
        {
            this.propunereAngajareCheltuialaBindingSource.Sort = "[Data] DESC";
            _frmNCR = new PACRezFrm(this.propunereAngajareCheltuialaBindingSource, fKPropunereAngajareCheltuialaDetaliuPropunereAngajareCheltuialaBindingSource, ModuleInfo);
            _frmNCR.MdiParent = this.MdiParent;
            //_frmNCR.LunaCurenta = LunaCurenta;
            _frmNCR.SelectionAddOn = true;
            _frmNCR.Show();
        }

        void Adapter_RowUpdated(object sender, SqlRowUpdatedEventArgs e)
        {
            if (e.StatementType == StatementType.Insert)
            {
                foreach (DataRow row in
                    eSRPDataSet.PropunereAngajareCheltuialaDetaliu.Select("IDPAC=" + e.Row["IDPAC", DataRowVersion.Original].ToString(),
                        "IDPAC", DataViewRowState.Added))
                {
                    row["IDPAC"] = e.Row["IDPAC"];
                }
            }
        }

        void PACFrm_HandleTiparire(object sender, EventArgs e)
        {
            Salvare(this, null);
            if (propunereAngajareCheltuialaBindingSource.Current == null || ((DataRowView)propunereAngajareCheltuialaBindingSource.Current).IsNew)
                return;


            SqlCommand cmd = new SqlCommand("", DeschideConexiune(workConnString));


            ESRPDataSet.PropunereAngajareCheltuialaRow dr = ((DataRowView)propunereAngajareCheltuialaBindingSource.Current).Row as ESRPDataSet.PropunereAngajareCheltuialaRow;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "CalcDisponibilPAC";
            cmd.Parameters.Add(new SqlParameter("CodUnitate", ModuleInfo.CodUnitate));
            cmd.Parameters.Add(new SqlParameter("IDPAC", dr.IDPAC));
            cmd.Parameters.Add(new SqlParameter("Data", dr.Data));
            cmd.ExecuteNonQuery();

            ESRPDataSet eSRPDS = new ESRPDataSet();
            Cursor.Current = Cursors.AppStarting;
            String linia1 = String.Empty, linia2 = String.Empty;
            


            PreviewRaportFrm frm = new PreviewRaportFrm("", null, ModuleInfo);
            //eSRPDataSet - este data setul cu care lucram

            foreach (BindingSource bs in listBS)
                if (bs != null) bs.Dispose();
            listBS.Clear();
            listBS.Add(new BindingSource(eSRPDS, "BalconSetup"));

            listTA.Clear();
            listTA.Add(new SqlDataAdapter("SELECT * FROM [BalconSetup] WHERE CodUnitate=" + ModuleInfo.CodUnitate.ToString(), cmd.Connection));
            listTA[0].SelectCommand.CommandType = CommandType.Text;
            listTA[0].Fill(eSRPDS.BalconSetup);

            listTA.Add(new SqlDataAdapter("SELECT * FROM [ExBugSetup] WHERE CodUnitate=" + ModuleInfo.CodUnitate.ToString(), cmd.Connection));
            listTA[1].SelectCommand.CommandType = CommandType.Text;
            listTA[1].Fill(eSRPDS.ExBugSetup);
            listBS.Add(new BindingSource(eSRPDS, "ExBugSetup"));

            listTA.Add(new SqlDataAdapter("SELECT * FROM [PropunereAngajareCheltuiala] WHERE IDPAC =" + dr["IDPAC"].ToString(), cmd.Connection));
            listTA[2].SelectCommand.CommandType = CommandType.Text;
            listTA[2].Fill(eSRPDS.PropunereAngajareCheltuiala);
            listBS.Add(new BindingSource(eSRPDS, "PropunereAngajareCheltuiala"));

            listTA.Add(new SqlDataAdapter("SELECT * FROM [PropunereAngajareCheltuialaDetaliu] WHERE IDPAC =" + dr["IDPAC"].ToString(), cmd.Connection));
            listTA[3].SelectCommand.CommandType = CommandType.Text;
            listTA[3].Fill(eSRPDS.PropunereAngajareCheltuialaDetaliu);
            listBS.Add(new BindingSource(eSRPDS, "PropunereAngajareCheltuialaDetaliu"));



            //String artAl = artAlCB.Text.Substring(0, 2);
            //String diviziune = JurnalCB.Text + "." + GetTitlu(artAl) + "." + artAlCB.Text;


            frm.NumeRaport = "PropunereAngajare.rdlc";

            frm.AddDataSource("ESRPDataSet_ExBugSetup", listBS[1]);
            frm.AddDataSource("ESRPDataSet_BalconSetup", listBS[0]);
            frm.AddDataSource("ESRPDataSet_PropunereAngajareCheltuiala", listBS[2]);
            frm.AddDataSource("ESRPDataSet_PropunereAngajareCheltuialaDetaliu", listBS[3]);
            frm.SetWindowFormat(true);

            

            foreach (SqlDataAdapter da in listTA)
                if (da != null) da.Dispose();
            listTA.Clear();
            InchideConexiune(cmd.Connection);
            frm.MdiParent = this.MdiParent;
            frm.Show();
            cmd.Dispose();
            


            Cursor.Current = Cursors.Default;
        }

        void PACFrm_HandleAfterAdd(object sender, DataGridViewCellEventArgs args)
        {
            String valnew = "1", valnewCFP = "1";
            Object ret = null;
            SqlCommand cmd = new SqlCommand("", DeschideConexiune(workConnString));

            if (SerieNumerica != String.Empty)
            {
                cmd.CommandText = "SELECT [UltimulNrFolosit] FROM [SeriiNumerice] WHERE IDSerie='" + SerieNumerica + "' AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
                ret = cmd.ExecuteScalar();
                if (ret != null && ret != DBNull.Value)
                {
                    valnew = ret.ToString();
                }
            }
            if (SerieNumericaCFP != String.Empty)
            {
                cmd.CommandText = "SELECT [UltimulNrFolosit] FROM [SeriiNumerice] WHERE IDSerie='" + SerieNumericaCFP + "' AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
                ret = cmd.ExecuteScalar();
                if (ret != null && ret != DBNull.Value)
                {
                    valnewCFP = ret.ToString();
                }
            }

            ///incrementarea seriei se face la salvare
            ///
            if (NoRecAdd > 0)
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "ActSeriiNumerice";
                if (SerieNumerica != String.Empty)
                {
                    
                    cmd.Parameters.Add(new SqlParameter("IDSerie", SerieNumerica));
                    cmd.Parameters.Add(new SqlParameter("CodUnitate", ModuleInfo.CodUnitate));
                    cmd.ExecuteNonQuery();
                }
                if (SerieNumericaCFP != String.Empty)
                {
                    cmd.Parameters.Clear();
                    cmd.Parameters.Add(new SqlParameter("IDSerie", SerieNumericaCFP));
                    cmd.Parameters.Add(new SqlParameter("CodUnitate", ModuleInfo.CodUnitate));
                    cmd.ExecuteNonQuery();
                }
                NoRecAdd--;
            }
            else
                NoRecAdd++;
            InchideConexiune(cmd.Connection);

            this.numarTB.Text = valnew;
            this.nrRegCFPTB.Text = valnewCFP;
            ActiveControl = numarTB;
        }

        /// <summary>
        /// citeste setarile din ResUmaSetup
        /// </summary>
        /// <param name="sqlConn"></param>
        private void LoadSetup(SqlConnection sqlConn)
        {
            Object ret = GetSetupValue("ExBugSetup", "AnulCurent", ModuleInfo.CodUnitate, sqlConn);
            /// nu a fost configurat modulul
            /// 
            while (ret == null)
            {
                MessageBox.Show("Modulul Executie Bugetara nu a fost configurat. \nVa rugam sa-l configurati!",
                        "Eroare",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Hand);
                ExBugSetupFrm frm = new ExBugSetupFrm(ModuleInfo);
                frm.ShowDialog();
                ret = GetSetupValue("ExBugSetup", "AnulCurent", ModuleInfo.CodUnitate, sqlConn);
            }
            AnulCurent = (Int16)ret;
            ret = GetSetupValue("ExBugSetup", "LunaCurenta", ModuleInfo.CodUnitate, sqlConn);
            LunaCurenta = (Int16)ret;

            SetInfoLunaAnul(LunaCurenta.ToString() + "," + AnulCurent.ToString());
            Object retObj = GetSetupValue("ExBugSetup", "IdSeriePAC", ModuleInfo.CodUnitate, sqlConn);
            if (retObj != null && retObj != DBNull.Value)
                SerieNumerica = retObj.ToString();

            retObj = GetSetupValue("ExBugSetup", "IdSerieCFP", ModuleInfo.CodUnitate, sqlConn);
            if (retObj != null && retObj != DBNull.Value)
                SerieNumericaCFP = retObj.ToString();

            ret = GetSetupValue("ExBugSetup", "CompartimentSpecialitate", ModuleInfo.CodUnitate, sqlConn);
            eSRPDataSet.PropunereAngajareCheltuiala.CompartimentColumn.DefaultValue = ret.ToString();

            ret = GetSetupValue("ExBugSetup", "OrdonatorCredite", ModuleInfo.CodUnitate, sqlConn);
            eSRPDataSet.PropunereAngajareCheltuiala.OrdonatorCrediteColumn.DefaultValue = ret.ToString();

            SqlCommand cmd = new SqlCommand("select TOP 1 [IDJurnal] from [Jurnale] where [CodUnitate]=" + ModuleInfo.CodUnitate.ToString() + " AND [Terminal]=1", sqlConn);
            ret = cmd.ExecuteScalar();
            if (ret != null)
            {
                eSRPDataSet.PropunereAngajareCheltuialaDetaliu.IDJurnalColumn.DefaultValue = Convert.ToInt32(ret);
            }
            cmd.CommandText = "select TOP 1 [ArtAl] from [ArticoleAliniate] where [CodUnitate]=" + ModuleInfo.CodUnitate.ToString() + "  AND [Terminal]=1" ;
            ret = cmd.ExecuteScalar();
            if (ret != null)
            {
                eSRPDataSet.PropunereAngajareCheltuialaDetaliu.ArtAlColumn.DefaultValue = ret.ToString();
            }

            cmd = new SqlCommand("SELECT TOP 1 o.IDResponsabil,Count(*) cate FROM [PropunereAngajareCheltuiala] o JOIN [ResponsabilVizaCFP] r on o.IDResponsabil=r.IDresponsabil  where o.[CodUnitate]=" + ModuleInfo.CodUnitate.ToString() + " GROUP BY o.IDResponsabil ORDER BY cate desc", sqlConn);
            ret = cmd.ExecuteScalar();
            if (ret != null)
            {
                //eSRPDataSet.PropunereAngajareCheltuialaDetaliu.IDJurnalColumn.DefaultValue = Convert.ToInt32(ret);
                eSRPDataSet.Ordonantari.IDResponsabilColumn.DefaultValue = Convert.ToInt32(ret);
            }

            //ret = GetSetupValue("ResUmaSetup", "Contracte", ModuleInfo.CodUnitate, sqlConn);
            //FolosesteContracte = Convert.ToInt16(ret) != 0;


        }

        private void PACFrm_Load(object sender, EventArgs e)
        {

            SqlConnection con = DeschideConexiune(workConnString);
            try
            {
                this.propunereAngajareCheltuialaDetaliuTableAdapter.Connection = con;
                this.propunereAngajareCheltuialaDetaliuTableAdapter.Fill(this.eSRPDataSet.PropunereAngajareCheltuialaDetaliu);
                jurnaleTableAdapter.Connection = con;
                jurnaleTableAdapter.Fill(eSRPDataSet.Jurnale, ModuleInfo.CodUnitate);
                
                articoleAliniateTableAdapter.Connection = con;
                articoleAliniateTableAdapter.FillByTerminal(eSRPDataSet.ArticoleAliniate, ModuleInfo.CodUnitate);
                this.persoaneVizaCFPTableAdapter.Connection = con;
                this.persoaneVizaCFPTableAdapter.Fill(this.eSRPDataSet.PersoaneVizaCFP, ModuleInfo.CodUnitate);

                this.propunereAngajareCheltuialaTableAdapter.Connection = con;
                propunereAngajareCheltuialaTableAdapter.Fill(this.eSRPDataSet.PropunereAngajareCheltuiala, ModuleInfo.CodUnitate);
                LoadSetup(con);
                InchideConexiune(con);
            }
            catch (System.Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
                return;
            }


            AddBindingSource(propunereAngajareCheltuialaBindingSource);
            AddTableAdaptor(propunereAngajareCheltuialaTableAdapter.Adapter);

            AddBindingSource(fKPropunereAngajareCheltuialaDetaliuPropunereAngajareCheltuialaBindingSource);
            AddTableAdaptor(propunereAngajareCheltuialaDetaliuTableAdapter.Adapter);

            if (ModuleInfo.CurrentTheme == String.Empty)
            {
                //AddButton("Salvare", global::ERPStudio.Properties.Resources.salvare1, Salvare, ToolStripItemAlignment.Right, true);
                AddButton("Generare AB", global::ERPStudio.Properties.Resources.bookmark, GenerareNC, ToolStripItemAlignment.Right, true);
                HandleSalvare += Salvare; 
            }
            else
            {
                AddButton("Incarca[F2]", global::ERPStudio.Properties.Resources.note, PAC_HandleRezumat, ToolStripItemAlignment.Left, true);
                AddButton("Sterge[F5]", global::ERPStudio.Properties.Resources.sterge, Sterge, ToolStripItemAlignment.Left, false);
                AddButton("Tipareste[F7]", global::ERPStudio.Properties.Resources.tipareste, PACFrm_HandleTiparire, ToolStripItemAlignment.Left, false);
                AddButton("Adauga[F8]", global::ERPStudio.Properties.Resources.adauga, Adauga, ToolStripItemAlignment.Left, false);
                EnableLocalSaveButton = false;
                AddButton("Salvare[F9]", global::ERPStudio.Properties.Resources.salvare, Salvare, ToolStripItemAlignment.Left, true);
                AddButton("Generare AB", global::ERPStudio.Properties.Resources.bookmark, GenerareNC, ToolStripItemAlignment.Right, true);


                HandleAdd += null;
                HandleMoveLast += Sterge;
                HandleSearch += PACFrm_HandleTiparire;
                HandleDel += Adauga;
                HandleSalvare += Salvare;
            }

            
            

            SetTitle();
            if (propunereAngajareCheltuialaBindingSource.Count == 0)
                Adauga(this, null);
        }

        private void GenerareNC(object sender, EventArgs e)
        {
            DataRowView dr = (DataRowView)propunereAngajareCheltuialaBindingSource.Current;
            if (dr == null || dr.IsNew)
            {
                MessageBox.Show("Generarea Angajamentului Bugetar se poate face doar pentru o propunere de cheltuiala salvata!",
                      "Eroare",
                      MessageBoxButtons.OK,
                      MessageBoxIcon.Stop);
                return;
            }
            ABFrm frm = new ABFrm(ModuleInfo);
            frm.MdiParent = this.MdiParent;
            frm.Show();
            frm.IDPACGenerare = Convert.ToInt32(dr["IDPAC"]);
        }

        private void vizatCFPCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            motivRefuzTB.Enabled = !vizatCFPCB.Checked;
        }

        private Decimal GetSum(String numeColoana)
        {
            Decimal total = Decimal.Zero;
            foreach (DataGridViewRow dr in PACDetaliuDGV.Rows)
            {
                if (dr.Cells[numeColoana].Value != DBNull.Value)
                    total += Convert.ToDecimal(dr.Cells[numeColoana].Value);
            }
            return total;
        } 

        override public void Salvare(object sender, EventArgs args)
        {
            MyTrace("Salvare");
            if (propunereAngajareCheltuialaBindingSource.Current!=null &&
                (fKPropunereAngajareCheltuialaDetaliuPropunereAngajareCheltuialaBindingSource.Count == 0))
            {
                MessageBox.Show("Este obligatorie adaugarea unei sume pe clasificatiile economice si bugetara!",
                      "Eroare",
                      MessageBoxButtons.OK,
                      MessageBoxIcon.Information);
                return;
            }
            base.Salvare(this, args);
            if (EroareSalvare)
                return;
            if (SerieNumerica != String.Empty)
                if (NoRecAdd > 0)
                {
                    SqlCommand cmd = new SqlCommand("", DeschideConexiune(workConnString));
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "ActSeriiNumerice";
                    cmd.Parameters.Add(new SqlParameter("IDSerie", SerieNumerica));
                    cmd.Parameters.Add(new SqlParameter("CodUnitate", ModuleInfo.CodUnitate));
                    cmd.ExecuteNonQuery();
                    if (SerieNumericaCFP != String.Empty)
                    {
                        cmd.Parameters.Clear();
                        cmd.Parameters.Add(new SqlParameter("IDSerie", SerieNumerica));
                        cmd.Parameters.Add(new SqlParameter("CodUnitate", ModuleInfo.CodUnitate));
                        cmd.ExecuteNonQuery();
                    }
                    InchideConexiune(cmd.Connection);
                    NoRecAdd = 0;
                }
            String newVal = GetSum("sumaColumn").ToString("N2");
            if (this.sumaTB.Text != newVal)
                this.sumaTB.Text = newVal;
        }

        override public void toolStripLabelAnLuna_Click(object sender, EventArgs e)
        {
            ExBugSetupFrm frm = new ExBugSetupFrm(ModuleInfo);
            frm.ShowDialog();
            this.OnActivated(null);
            ///actualizare unitate la copi
            foreach (Form frmChild in this.MdiParent.MdiChildren)
            {
                //if (frmChild != this)
                ((StudioForm)frmChild).SetCurentMonth(ModuleInfo.CodUnitate);
            }
        }

        override public void SetCurentMonth(short vCodUnitate)
        {
            SqlConnection con=DeschideConexiune(workConnString);
            LoadSetup(con);
            InchideConexiune(con);
        }

        private void PACDetaliuDGV_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            MyTrace("rulajeDGV_CellValueChanged " + e.RowIndex.ToString() + ",coloana=" + e.ColumnIndex.ToString());
            if (e.RowIndex == -1)
                return;
            String newVal;

            if (PACDetaliuDGV.Columns["sumaColumn"] != null)
            {
                if (PACDetaliuDGV.Columns["sumaColumn"].Index == e.ColumnIndex)
                {
                    newVal = GetSum("sumaColumn").ToString("N2");
                    if (this.sumaTB.Text != newVal)
                        this.sumaTB.Text = newVal;
                }
            }
        }
        /// <summary>
        /// functie apelata pentru a calcula suma in cazul stergerii unei linii
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        new public void Sterge(object sender, EventArgs args)
        {
            String newVal = GetSum("sumaColumn").ToString("N2");
            if (this.sumaTB.Text != newVal)
                this.sumaTB.Text = newVal;

        }
    }
}
